package com.adam.springbuck.service;

import com.adam.springbuck.entity.Person;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Service
public class BuckRPCServiceImpl implements BuckRPCService {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * RPC方式一：RestTemplate
     *
     * @param id
     * @return
     */
    @Override
    public Person getRPCRestTemp(Long id) {
        Person p = restTemplate.getForObject("http://localhost:8082/json?id=" + id, Person.class);
        log.info("restTemplate==>p:{}", p);
        return p;
    }


    /**
     * RPC方式二：http
     *
     * @param id
     * @return
     */
    @Override
    public Person httpRPC(Long id) {
        Person person = new Person(100L,"dada",25);
        try {
            //创建http工具（理解成:浏览器） 发起请求，解析响应
            CloseableHttpClient aDefault = HttpClients.createDefault();
            //请求路径
            URIBuilder uriBuilder = new URIBuilder("http://localhost:8082/json?id=" + id);
            //创建HttpGet请求对象
            HttpGet get = new HttpGet(uriBuilder.build());
            //创建响应对象
            CloseableHttpResponse execute = aDefault.execute(get);
            //由于响应体是字符串，因此把HttpEntity类型转换为字符串类型，并设置字符编码
            String s = EntityUtils.toString(execute.getEntity(), "UTF-8");
            //输出结果
            log.info("httpRPC:" + s);
            person = JSONObject.parseObject(s, Person.class);
            //释放资源
            execute.close();
            aDefault.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return person;
    }


}
